<?php

class FeedbackAction extends fvAction {
	
	function __construct() {
		parent::__construct ( fvSite::$Layoult );
	}
	
	function executeIndex() {
		if (! fvRequest::getInstance ()->isXmlHttpRequest ()) {
			return self::$FV_OK;
		} else {
			return self::$FV_AJAX_CALL;
		}
	}
	
	function executeSavetext() {
		$Feedback = new Feedback ( );
		$request = fvRequest::getInstance ();
		$m = $request->getRequestParameter ( 'm' );
		if (! $m ['country_id']) {
			$Feedback->setValidationResult ( "country_id", false, "Необходимо выбрать страну" );
		}
		if (empty ( $m ['date_to'] )) {
			$Feedback->setValidationResult ( "date_to", false, "Дата окончания отдыха должна быть заполнена" );
		}
		if (empty ( $m ['date_from'] )) {
			$Feedback->setValidationResult ( "date_from", false, "Дата начала отдыха должна быть заполнена" );
		}
		if ($m ['date_from'] > $m ['date_to']) {
			$Feedback->setValidationResult ( "dates_error", false, "Дата начала не может быть больше даты окончания отдыха" );
		}
		if ($m ['date_from'] > date ( "Y-m-d" ) || $m ['date_to'] > date ( "Y-m-d" )) {
			$Feedback->setValidationResult ( "dates_error2", false, "Дата не может быть больше сегодняшней" );
		}
		if (count ( $m ['feedbacktypes_id'] ) < 1) {
			$Feedback->setValidationResult ( "feedbacktypes_id", false, "Необходимо указать хотя бы один тип отзыва" );
		}
		if (! $m ['accept_rules']) {
			$Feedback->setValidationResult ( "accept_rules", false, "Необходимо ознакомиться с правилами использования" );
		}
		$login = $request->getRequestParameter ( 'login' );
		if (! fvSite::$fvSession->getUser ( "login/loggedUser" ))
			if (! $login) {
				$Feedback->setValidationResult ( "login", false, "Введите логин и пароль" );
			} else {
				if ($loggedUser = UserManager::getInstance ()->Login ( $login ['login'], $login ['password'] )) {
					fvSite::$fvSession->setUser ( $loggedUser );
				} else {
					$Feedback->setValidationResult ( "login2", false, "Проверьте пару логин-пароль" );
				}
			}
		unset ( $m ['accept_rules'] );
		if (! $Feedback->getValidationResult ()) {
			$Feedback->updateFromRequest ( $m );
			$Feedback ['user_id'] = fvSite::$fvSession->getUser ( "login/loggedUser" )->getPk ();
			$Feedback ['is_show'] = 0;
			if ($Feedback->save ()) {
				fvSite::$fvSession->set ( "feedback_id", $Feedback->getPk () );
				if ($request->getRequestParameter ( 'redirect' ) == 'video')
					$this->redirect ( "@feedback/addvideo/" );
				else {
					$this->redirect ( "@feedback/success/" );
				}
			} else
				fvSite::$fvSession->set ( "ERROR", "Произошла ошибка при сохранении." );
		} else {
			fvSite::$fvSession->set ( "ERROR", $Feedback->getValidationResult () );
			fvSite::$fvSession->set ( "m", $m );
		}
		$this->redirect ( "@feedback/addtext/" );
	}
	
	function executeUploadvideofile() {
		$r = fvRequest::getInstance ();
		if ($r->isFileUpload ( 'videofile' ) && ($r->checkUploadFile ( 'videofile' ) == fvRequest::ERROR_SUCCESS)) {
			$tmp_dir = fvSite::$fvConfig->get ( 'path.upload.tmp_dir' );
			$fileName = $r->getUploadFileName ( 'videofile' );
			$r->saveUploadData ( 'videofile', $tmp_dir . $fileName );
			$fileNames = explode ( '.', $fileName );
			$video_size = $r->getVideoSize ( $tmp_dir . $fileName );
			$x = 50 / $video_size ['width'];
			$uv_height = ceil ( $video_size ['height'] * $x );
			exec("export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/tv/ffmpeg/lame/lib;nohup ffmpeg -i " . $tmp_dir . $fileName . " -an -ss 00:00:05 -r 1 -vframes 1 -s 50?" . $uv_height . " -y -f mjpeg " . $tmp_dir . $fileNames [0] . "-thumb.jpg &" );
			fvParams::getInstance ()->setParameter ( fvRoute::getInstance ()->getModuleName () . "/filename", $fileName );
		}
		echo $fileName;
		die ();
	}
	
	function executeUploadimagefile() {
		$r = fvRequest::getInstance ();
		if ($r->isFileUpload ( 'imagefile' ) && ($r->checkUploadFile ( 'imagefile' ) == fvRequest::ERROR_SUCCESS)) {
			$tmp_dir = fvSite::$fvConfig->get ( 'path.upload.tmp_dir' );
			$fileName = $r->getUploadFileName ( 'imagefile' );
			$r->saveUploadData ( 'imagefile', $tmp_dir . $fileName );
			fvParams::getInstance ()->setParameter ( fvRoute::getInstance ()->getModuleName () . "/filename", $fileName );
		}
		echo $fileName;
		die ();
	}
	
	function executeSaveuploadvideo() {
		$request = fvRequest::getInstance ();
		$LoggedUser = fvSite::$fvSession->get ( "login/loggedUser" );
		$m = $request->getRequestParameter ( 'alt_text' );
		$feedback_id = fvSite::$fvSession->get ( "feedback_id" );
		$file = $request->getRequestParameter ( 'hidFileID' );
		$Video = new Video ( );
		$Video->alt_text = $m;
		$file_data = explode ( '.', $file );
		$Video->file_name = $file_data [0];
		$Video->file_extension = $file_data [1];
		$Video->user_id = $LoggedUser->getPk ();
		$Video->feedback_id = $feedback_id;
		$Video->is_show = 0;
		$Video->save ();
		$this->redirect ( "@feedback/addvideo/" );
	}
	
	function executeSaveuploadimage() {
		$request = fvRequest::getInstance ();
		$LoggedUser = fvSite::$fvSession->get ( "login/loggedUser" );
		$m = $request->getRequestParameter ( 'alt_text' );
		$feedback_id = fvSite::$fvSession->get ( "feedback_id" );
		$file = $request->getRequestParameter ( 'hidFileID' );
		$Image = new Image ( );
		$Image->alt_text = $m;
		$Image->file_name = $file;
		$Image->user_id = $LoggedUser->getPk ();
		$Image->feedback_id = $feedback_id;
		$Image->is_show = 0;
		$Image->save ();
		$this->redirect ( "@feedback/addimage/" );
	}
	
	function executeSavevideo() {
		$request = fvRequest::getInstance ();
		$feedback_id = fvSite::$fvSession->get ( "feedback_id" );
		$LoggedUser = fvSite::$fvSession->get ( "login/loggedUser" );
		$Videos = VideoManager::getInstance ()->getAll ( "is_show=0 and feedback_id=" . $feedback_id . " and user_id=" . $LoggedUser->getPk () );
		$tmp_dir = fvSite::$fvConfig->get ( 'path.upload.tmp_dir' );
		foreach ( $Videos as $Video ) {
			$video_size = $request->getVideoSize ( $tmp_dir . $Video->file_name . "." . $Video->file_extension );
			$directory = $Video->getDir ();
			$x = 320 / $video_size ['width'];
			$uv_height = ceil ( $video_size ['height'] * $x );
			passthru ( "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/tv/ffmpeg/lame/lib;nohup ffmpeg -i /home/tv/web/upload/tmp/" . $Video->file_name . "." . $Video->file_extension . " -acodec mp3 -ar 44100 -ab 64 -s 320x" . $uv_height . " -b 700k " . $directory . "/" . $Video->file_name . ".flv >& /dev/null &" );
			$Video->is_show = 1;
			$Video->save ();
		}
		if ($request->getRequestParameter ( 'redirect' ) == 'image')
			$this->redirect ( "@feedback/addimage/" );
		else {
			
			$this->redirect ( "@feedback/success/" );
		}
	}
	
	function executeSaveimage() {
		$request = fvRequest::getInstance ();
		$feedback_id = fvSite::$fvSession->get ( "feedback_id" );
		$LoggedUser = fvSite::$fvSession->get ( "login/loggedUser" );
		$Images = ImageManager::getInstance ()->getAll ( "feedback_id=" . $feedback_id . " and user_id=" . $LoggedUser->getPk () );
		$tmp_dir = fvSite::$fvConfig->get ( 'path.upload.tmp_dir' );
		foreach ( $Images as $Image ) {
			//			$video_size = $request->getVideoSize($tmp_dir . $Video->file_name.".".$Video->file_extension);
			$Image->saveUploadFile ( 'file_name', fvSite::$fvConfig->get ( 'path.upload.tmp_dir' ) . $Image->file_name, 'xml' );
			$Image->is_show = 1;
			$Image->save ();
		}
		$this->redirect ( "@feedback/success/" );
	}
	
	function executePublish() {
		$request = fvRequest::getInstance ();
		if ($request->getRequestParameter ('id')) {
			$Feedback = FeedbackManager::getInstance ()->getByPk ( $request->getRequestParameter  ( 'id' ) );
			$Feedback->is_show = 3;
			$Feedback->save();
			$update['is_show'] = 3;
			VideoManager::getInstance()->massUpdate("feedback_id=".$request->getRequestParameter('id'), $update);
			ImageManager::getInstance()->massUpdate("feedback_id=".$request->getRequestParameter('id'), $update);
		}
		$this->redirect ( "@feedback/moderate/" );
	}
	
	function executeDeletevideo(){
		$request = fvRequest::getInstance();
        if (!$Video = VideoManager::getInstance()->getByPk($request->getRequestParameter('id'))) {
            $this->setFlash("Ошибка при удалении.", self::$FLASH_ERROR);
        } else {
        	$back = $Video->feedback_id;
        	unlink('/home/tv/web/upload/video/'.str_pad($Video->user_id, 8, '0', STR_PAD_LEFT).'/'.$Video->file_name.'.flv');
            $Video->delete();
        } 
        $this->redirect ( "@feedback/moderate/?id=".$back );
	}
	
	function executeDeleteimage(){
		$request = fvRequest::getInstance();
        if (!$Image = ImageManager::getInstance()->getByPk($request->getRequestParameter('id'))) {
            $this->setFlash("Ошибка при удалении.", self::$FLASH_ERROR);
        } else {
        	$back = $Image->feedback_id;
        	unlink('/home/tv/web/upload/images/'.str_pad($Image->user_id, 8, '0', STR_PAD_LEFT).'/'.$Image->file_name);
            $Image->delete();
        } 
        $this->redirect ( "@feedback/moderate/?id=".$back );
	}
	
	function executeSave() {
		if (! fvRequest::getInstance ()->isXmlHttpRequest ()) {
			return self::$FV_OK;
		} else {
			return self::$FV_AJAX_CALL;
		}
	}
	
	function executeChangecountry(){
    	if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_AJAX_CALL;
        else $this->redirect404();
    }
    
	function executeChangeresort(){
    	if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_AJAX_CALL;
        else $this->redirect404();
    }

}

?>
